package cn.edu.swu.syz.controller;

import cn.edu.swu.syz.db.DatabaseService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/addBook") // 确保此路径与表单action一致
public class AddBookServlet extends HttpServlet {
    private DatabaseService dbService;

    // 初始化时获取 DatabaseService 单例（与项目其他Servlet保持一致）
    @Override
    public void init() {
        dbService = DatabaseService.getInstance(); // 关键：使用单例模式
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 设置请求编码，解决中文乱码
        request.setCharacterEncoding("UTF-8");

        // 2. 获取表单参数
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String price = request.getParameter("price");
        String memo = request.getParameter("memo");
        String publish = request.getParameter("publish");

        // 3. 简单验证参数（避免空值导致SQL错误）
        if (name == null || name.trim().isEmpty() || price == null || price.trim().isEmpty()) {
            throw new ServletException("书名和价格不能为空");
        }

        // 4. 使用参数化SQL，避免SQL注入（重要！）
        String insertSQL = "insert into book (name, author, price, memo, publish) " +
                "values (?, ?, ?, ?, ?)";

        try {
            // 调用参数化execute方法，传递参数
            dbService.execute(insertSQL, name, author, price, memo, publish);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException("添加图书失败：" + e.getMessage());
        }

        // 5. 重定向回图书列表页
        response.sendRedirect("./books");
    }

    // 处理意外的GET请求（避免用户直接访问/addBook时出错）
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 重定向到添加图书页面或图书列表页
        response.sendRedirect("./addBook.jsp"); // 假设添加页面是addBook.jsp
    }
}